﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace nRoute.Samples.Netflix.Controls
{
    public partial class WorkingIndicator 
        : UserControl
    {
        public static readonly DependencyProperty IsWorkingProperty =
            DependencyProperty.Register("IsWorking", typeof(bool), typeof(WorkingIndicator),
            new PropertyMetadata(false, new PropertyChangedCallback(OnIsWorkingChanged)));

        private Storyboard _workingStoryboard;

        public WorkingIndicator()
        {
            InitializeComponent();
            _workingStoryboard = this.Resources["WorkingStoryboard"] as Storyboard;
        }

#region Properties

        [Category("Common Properties")]
        public bool IsWorking
        {
            get { return Convert.ToBoolean(GetValue(IsWorkingProperty)); }
            set { SetValue(IsWorkingProperty, value); }
        }

#endregion

#region Handlers

        private static void OnIsWorkingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((WorkingIndicator)d).UpdateIsWorking(Convert.ToBoolean(e.NewValue));
        }

        private void UpdateIsWorking(bool value)
        {
            this.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
            if (value)
            {
                this.LayoutRoot.Visibility = Visibility.Visible;
                this._workingStoryboard.Begin();
            }
            else
            {
                this.LayoutRoot.Visibility = Visibility.Collapsed;
                this._workingStoryboard.Stop();
            }
        }

#endregion

    }
}
